package com.my.study.service;

import com.my.study.common.ServerConnectClientThread;
import com.my.study.common.message.Message;
import com.my.study.common.message.MessageType;
import com.my.study.common.message.User;
import com.my.study.manage.ManageServerConnectClientThread;
import com.my.study.utils.SteamCloseUtils;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Carlos
 * @version 1.0
 * @Description TODO
 * @date 2021/7/18 14:50
 **/
public class QQServer {

    private ServerSocket serverSocket;

    private String USER_ID = "100";
    private String PWD = "123456";

    public QQServer() {
        try {
            System.out.println("服务端在9999端口监听...");
            serverSocket = new ServerSocket(9999);

            while (true) {
                Socket socket = serverSocket.accept();
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                User user = (User) ois.readObject();
                Message message = new Message();
                // 验证
                if (checkUser(user)) {
                    message.setMsgType(MessageType.MESSAGE_LOGIN_SUCCEED);
                    oos.writeObject(message);
                    // 创建一个线程，和客户端保持通信
                    ServerConnectClientThread scct = new ServerConnectClientThread(socket, user.getUserId());
                    scct.start();
                    ManageServerConnectClientThread.addServerConnectClientThread(user.getUserId(), scct );
                }
                else {
                    message.setMsgType(MessageType.MESSAGE_LOGIN_FAIL);
                    oos.writeObject(message);
                    socket.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            SteamCloseUtils.close(serverSocket, () -> "");
        }
    }

    private boolean checkUser(User user) {
        String userId = user.getUserId();
        String pwd = user.getPwd();
        return USER_ID.equals(userId) && PWD.equals(pwd);
    }
}
